import { app, BrowserWindow, ipcMain, Menu, Tray } from 'electron'
import { electronApp, optimizer } from '@electron-toolkit/utils'
import { getMenuOptions } from './composables/contextMenu'
import { waterIcon } from './composables/icon'
import { createMainWindow } from './composables/mainWindow'
import { setAutoOpenStatus } from './composables/storageUtils'

function createWindow(): void {
  // 创建主窗口
  const mainWin = createMainWindow()
  // 创建系统托盘
  const tray = new Tray(waterIcon);
  // 构建系统托盘的右键菜单
  const contextMenu = Menu.buildFromTemplate(getMenuOptions(mainWin.getWindow()!))
  // 设置系统托盘的右键菜单
  tray.setContextMenu(contextMenu)
  // 设置系统托盘的提示信息
  tray.setToolTip('计数器')

  // 展示窗口
  mainWin.show()
  mainWin.initWinPosition("mainWinPosition")
}

// 当你不需要默认菜单时调用，提高启动性能
Menu.setApplicationMenu(null)

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.zero.counter')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))

  // ipcMain.handle('get-path', ()=> {
  //   // 获取当前路径
  //   dirname(app.getPath('exe'))
  // })

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })

  setAutoOpenStatus()
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
